package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.service.CommonService;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author bairimengchang
 * @version 1.0
 * @project sky-take-out
 * @description 通用业务接口实现类
 * @date 2024/08/13 16:35:40
 */
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Autowired
    private AliOssUtil aliOssUtil;      //阿里OSS文件上传工具类

    /**
     * 文件上传
     * @param file 要上传的文件
     * @return 对应的阿里OSS的访问url地址，或者错误信息字符串
     */
    @Override
    public String upload(MultipartFile file) {
        String filePath;
        try {
            String originalFilename = file.getOriginalFilename();
            //拿文件后缀
            if (originalFilename != null) {
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                //新文件名称
                String objectName = UUID.randomUUID() + extension;
                filePath = aliOssUtil.upload(file.getBytes(), objectName);
                log.info("返回的阿里OSS地址:{}", filePath);
                return filePath;
            }
        } catch (IOException e) {
            log.error("控制器报错，具体报错信息:{}", e.getMessage());
            return MessageConstant.UPLOAD_FAILED;
        }
        return "上传信息因未知原因失败，业务实现类报错！";
    }
}
